
package com.lzx.iteam.adapter;

import android.content.ContentUris;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.database.Cursor;
import android.graphics.*;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.ContactsContract.CommonDataKinds;
import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.Website;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.*;
import com.lzx.iteam.CloudDialerActivity;
import com.lzx.iteam.ContactDetailActivity;
import com.lzx.iteam.DialerApp;
import com.lzx.iteam.R;
import com.lzx.iteam.bean.ChatContact;
import com.lzx.iteam.bean.SkinCommonData;
import com.lzx.iteam.contactssearch.ContactsDBReader;
import com.lzx.iteam.contactssearch.ContactsDBReader.GroupInfo;
import com.lzx.iteam.contactssearch.conversion.Addressbook.Person;
import com.lzx.iteam.contactssearch.conversion.Addressbook.Person.GroupIdSet;
import com.lzx.iteam.contactssearch.conversion.PinyinSearch;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.util.*;
import com.lzx.iteam.widget.RoundImageView;

import java.util.*;

import static com.lzx.iteam.R.id.footer_body;

public class ContactEntryAdapter extends AmazingAdapter implements OnSharedPreferenceChangeListener, OnLongClickListener, OnClickListener {

    protected LayoutInflater mInflater;

    private CloudDialerActivity mContext;

    private String mCurrentSearchText;

    private boolean mDisplayNameOnly = false;
    private boolean mIsPhotoShow = true;
    private boolean mIfCheckBoxShow = false;

//    private int mOrderBy;

    protected static final int TYPE_NORMAL = 1;

    protected static final int TYPE_HEADER = 0;

    protected static final int TYPE_FOOTER = 2;

    protected static final int TYPE_COUNT = 3;

    List<Pair<String, List<Long>>> mAllContactsIdBySection;
    public List<Pair<String, List<Long>>> mSelectedContactsIdBySection;
    public List<Pair<String, List<Long>>> mBackAllContactsIdBySection;

    private HashMap<Long, String> registUsers;

    private PinyinSearch mPinyinSearch;

    private PreferenceUtil mPreferenceUtil;

    private DialerApp dialerapp;

    private ArrayList<Long> mContactIdSelected = new ArrayList<Long>();
    private ArrayList<ChatContact> mContactSelected = new ArrayList<ChatContact>();
    private ArrayList<String> mNameCard = new ArrayList<String>();//名片信息，用于获取我的名字发短信

    private HashMap<Long, Integer> mCloudUserData = new HashMap<Long, Integer>();
    private HashMap<Long, String> mCloudUser = new HashMap<Long, String>();

    private boolean mInterrupted = false;

    public View mTouchView = null;
    Long selectedId;
    private String mWxIds;
    private String mMyName;// 我的名字
    Drawable noName;

    
    /*public void clearSelectedStatus()
    {
    	clearSelectedStatus(mTouchView);
    	this.notifyDataSetChanged();
    }*/
    
    /*public void clearSelectedStatus(View view) {
        if (view != null) {
            ContactEntryHolder holder = (ContactEntryHolder) view.getTag();
            if (holder != null) {
                if (holder.contactId.equals(selectedId)) {
                    selectedId = null;
                }
                holder.nameTextView.setTextColor(mSkin.nameColor);
                holder.numberTextView.setTextColor(mSkin.phoneColor);
                holder.timesContactedView.setTextColor(mSkin.phoneColor);
                holder.orgTextView.setTextColor(mSkin.jobTitleColor);
                holder.maskImg.setImageResource(R.drawable.mask);
                view.setBackgroundResource(R.color.transbg);
            }
        }
    }*/

    public void setNoNameDrawable(Drawable d) {
        this.noName = d;
    }

    private Drawable getNoNameDrawable() {
        if (noName == null) {
            noName = mContext.getResources().getDrawable(R.drawable.default_cloud_image);
        }
        return noName;
    }

    public void setInterrupted(boolean interrupted) {
        mInterrupted = interrupted;
    }

//    public int getCurrentPage() {
//        return mContext.getCurrentPage();
//    }
//
//    public void setSelect(int index) {
//        mContext.setSelect(index);
//    }

    /**
     * 设置选中状态
     *
     * @param view
     */
    /*public void setSelectedStatus(View view) {
        if (view != null) {
            ContactEntryHolder holder = (ContactEntryHolder) view.getTag();
            if (holder != null) {
//                holder.nameTextView.setSelected(selected);
                holder.nameTextView.setTextColor(Color.WHITE);
                holder.orgTextView.setTextColor(Color.WHITE);
                holder.timesContactedView.setTextColor(Color.WHITE);
                holder.numberTextView.setTextColor(Color.WHITE);
                holder.maskImg.setImageResource(R.drawable.mask_pressed);
                view.setBackgroundResource(R.drawable.centersel_pressed);
            }
         *//*   ContactEntryHolder holder = (ContactEntryHolder) mTouchView.getTag();
            if (holder != null) {
                holder.nameTextView.setTextColor(0xffffffff);
                holder.numberTextView.setTextColor(0xffffffff);
                holder.orgTextView.setTextColor(0xffffffff);
            }*//*
        }
//        notifyDataSetChanged();
    }*/

    public void setIfCheckBoxShow(boolean show) {
        this.mIfCheckBoxShow = show;
        mContactIdSelected.clear();
        mContactSelected.clear();
        selectedId = null;
    }

    public void setIfCheckBoxShowNoClear(boolean show) {
        this.mIfCheckBoxShow = show;
    }

    public void clearSelected() {
        mContactIdSelected.clear();
        mContactSelected.clear();

    }

    public void selectAllContacts(ArrayList<ChatContact> allContacts) {
        if (mContactSelected.size() == 0) {
            mContactSelected.addAll(allContacts);
            if (allContacts.size() != 0) {
                mContext.setSelectImage(true);
            }
        } else {
            mContactSelected.clear();
            mContext.setSelectImage(false);
        }
        /*if (allContactsId.size() > mContactIdSelected.size()) {
            mContactIdSelected.clear();
            mContactIdSelected.addAll(allContactsId);
        } else {
            mContactIdSelected.clear();
        }*/
        this.notifyDataSetChanged();
    }

    public void selectAllContactIds(ArrayList<Long> allContactsId,boolean select) {
        if (/*mContactIdSelected.size() == 0*/select == true) {
            mContactIdSelected.clear();
            mContactIdSelected.addAll(allContactsId);
            if (allContactsId.size() != 0)
            {
                mContext.setSelectImage(true);
            }
        } else {
//        	allContactsId.clear();
            mContactIdSelected.clear();
            mContext.setSelectImage(false);
        }
        /*if (allContactsId.size() > mContactIdSelected.size()) {
            mContactIdSelected.clear();
            mContactIdSelected.addAll(allContactsId);
        } else {
            mContactIdSelected.clear();
        }*/
        this.notifyDataSetChanged();
    }

    public boolean getIfCheckBoxShow() {
        return mIfCheckBoxShow;
    }

    public ArrayList<ChatContact> getSelectedContacts() {
        return mContactSelected;
    }

    public ArrayList<Long> getSelectedContactIds() {
        return mContactIdSelected;
    }

    private SkinCommonData mSkin;

    public ContactEntryAdapter(final LayoutInflater inflater,
                               final CloudDialerActivity aContext, List<Pair<String, List<Long>>> contactIds) {
        // super(aContext, R.layout.search_contact_item, null);

        mContext = aContext;

        mInflater = inflater;

        mAllContactsIdBySection = contactIds;

//        dialerapp = (DialerApp) mContext.getApplication();
//        mPinyinSearch = dialerapp.getPinyinSearch();
        mPreferenceUtil = PreferenceUtil.getInstance(mContext);

        // 初始化用于划屏时的相关常量
        //mIsPhotoShow = mPreferenceUtil.get(PreferenceUtil.CONTACT_ISDISPLAYPHOTO, Boolean.class);
        mDisplayNameOnly = mPreferenceUtil.get(PreferenceUtil.DISPLAY_NAME_ONLY, Boolean.class);
        //mDisplayNameOnly = mPreferenceUtil.getBoolean(PreferenceUtil.DISPLAY_NAME_ONLY,true);


//        mOrderBy = dialerapp.getPreferenceUtil().get(PreferenceUtil.CONTACT_NAME_SORT, Integer.class);
        mPreferenceUtil.registerOnSharedPreferenceChangeListener(
              PreferenceUtil.CONTACT_ISDISPLAYPHOTO, this);
        mPreferenceUtil.registerOnSharedPreferenceChangeListener(
              PreferenceUtil.CONTACT_NAME_SORT, this);
        mPreferenceUtil.registerOnSharedPreferenceChangeListener(
              PreferenceUtil.DISPLAY_NAME_ONLY, this);
//        if (mCloudUser == null || mCloudUser.size()==0){
//            mCloudUser = (HashMap<Long, String>) mPreferenceUtil.getCloudContact(PreferenceUtil.CLOUD_REGIST_USER);
//        }

        mNameCard = (ArrayList<String>) mPreferenceUtil.getCloudContact(Constants.CONTACT_NAME_CARD);
        if (mNameCard != null && mNameCard.size() > 0){
            mMyName = mNameCard.get(0);
        }
        if (StringUtil.isEmpty(mMyName)){
            mMyName = mPreferenceUtil.getString("my_user_name","");
        }
    }

    public void changeContent(List<Pair<String, List<Long>>> contactIds) {
        mAllContactsIdBySection = contactIds;
        notifyDataSetChanged();
    }

    /**
     * 仅显示已选
     */
    public void changeSelectedContent() {
        if (mContactIdSelected != null) {
            if (mBackAllContactsIdBySection != null) {
                mBackAllContactsIdBySection.clear();
                mBackAllContactsIdBySection.addAll(mAllContactsIdBySection);
            } else {
                mBackAllContactsIdBySection = new ArrayList<Pair<String, List<Long>>>();
                mBackAllContactsIdBySection.addAll(mAllContactsIdBySection);
            }

            Pair pair = new Pair("常用", mContactIdSelected);
            mSelectedContactsIdBySection = new ArrayList<Pair<String, List<Long>>>();
            mSelectedContactsIdBySection.add(pair);
            mAllContactsIdBySection = mSelectedContactsIdBySection;
            notifyDataSetChanged();
        }
    }

    /**
     * 恢复显示全部
     */
    public void changeToAllContent() {
        if (mBackAllContactsIdBySection != null)
        {
            mAllContactsIdBySection.clear();
            if (mBackAllContactsIdBySection != null)
            {
                mAllContactsIdBySection.addAll(mBackAllContactsIdBySection);
            }
            notifyDataSetChanged();
            
            /*
            int sumvalid = 0;
            for (Pair<String, List<Long>> item : mAllContactsIdBySection)
            {
                if (isHaveUnClickable) 
                {
                    for (Long id : item.second)
                    {
                        if (isHaveUnClickable && mCloudUser.get(id) == null) 
                        {
                        } 
                        else 
                        {
                        	sumvalid++;
                        }
                    }
                }
                else 
                {
                }
            }
            
            if( mContactSelected.size() == sumvalid )
            {
            	mContext.mCbSelectAll.setChecked(true);
            }
            else 
            {
            	mContext.mCbSelectAll.setChecked(false);
            }
 			*/
        }
    }

    public void setSkin(SkinCommonData skin) {
        mSkin = skin;
    }

    public List<Long> getChangeContentId() {
        List<Long> list = null;
        List<Long> newList = new ArrayList<Long>();
        for (Pair<String, List<Long>> item : mAllContactsIdBySection) {
            if (isHaveUnClickable) {
                list = new ArrayList<Long>();
                for (Long id : item.second) {
                    if (isHaveUnClickable && mCloudUser.get(id) == null) {
                    } else {
                        list.add(id);
                    }
                }
                newList.addAll(list);
            } else {
                list = item.second;
                newList.addAll(list);
            }
        }

        return newList;
    }

    private boolean isHaveUnClickable = false;

    public void setLocalContactCheckStyle(boolean isHaveUnClickable) {
        this.isHaveUnClickable = isHaveUnClickable;
        notifyDataSetChanged();
    }

    public void setCloudUserData(HashMap<Long, Integer> cloudUserData) {
        if (cloudUserData != null) {
            mCloudUserData = cloudUserData;
        } else {
            mCloudUserData.clear();
        }
        notifyDataSetChanged();
    }

    public void setCloudUser(HashMap<Long, String> cloudUser) {
        if (cloudUser != null) {
            mCloudUser = cloudUser;
        } else {
            mCloudUser.clear();
        }
        notifyDataSetChanged();
    }


    @Override
    public int getCount() {

        int res = 0;
        int size = getAllContactsIdSize();
        for (int i = 0; i < size; i++) {
            res += mAllContactsIdBySection.get(i).second.size();
        }
        // plus 1 for footer view
        return res + 1-1;
    }


    @Override
    public Long getItem(int position) {

        int c = 0;

        int size = getAllContactsIdSize();
        for (int i = 0; i < size; i++) {
            if (position >= c && position < c + mAllContactsIdBySection.get(i).second.size()) {
                return mAllContactsIdBySection.get(i).second.get(position - c);
            }
            c += mAllContactsIdBySection.get(i).second.size();
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    protected void onNextPageRequested(int page) {
    }

    @Override
    protected void bindSectionHeader(View view, int position, boolean displaySectionHeader) {
        if (view != null) {
            if (displaySectionHeader) {
                view.findViewById(R.id.composer_header).setVisibility(View.GONE);
                TextView lSectionTitle = (TextView) view.findViewById(R.id.composer_header);
                lSectionTitle.setText(getSections()[getSectionForPosition(position)]);
            } else if (position == (getCount() - 1)) {

            } else {
                view.findViewById(R.id.composer_header).setVisibility(View.GONE);
            }
        }
    }


    public static final class ContactEntryHolder {

        public ImageView contactDisturbStatus;

        public CheckBox checkBox;

        public TextView nameTextView;

        public TextView timesContactedView;

        public TextView orgTextView;

        public TextView numberTextView;

        public RoundImageView quickContact;

        public Long contactId;

        public String phoneNum;

        public ImageView wxIcon;

        //public ImageView maskImg;
        public ImageView inviteImg;
    }

    public void setCurrentSearchText(String searchText) {
        this.mCurrentSearchText = searchText;
    }

    @Override
    public View getAmazingView(int position, View convertView, ViewGroup parent) {
        Long contactId = getItem(position);
        mWxIds = mPreferenceUtil.getString(Constants.WX_IDS_SET, "");
        ContactEntryHolder holder = null;
        if (contactId != null) {
            if (convertView == null || convertView instanceof LinearLayout) {
                convertView = mInflater.inflate(R.layout.search_contact_item, null);
            }
            holder = (ContactEntryHolder) convertView.getTag();
            if (holder == null) {
                holder = new ContactEntryHolder();
            }
            holder.contactDisturbStatus = (ImageView) convertView.findViewById(
                  R.id.contact_disturb_status);
            holder.nameTextView = (TextView) convertView.findViewById(R.id.search_contact_name);
            holder.nameTextView.setTextColor(nameColor);
            holder.timesContactedView = (TextView) convertView.findViewById(R.id.contact_count);
            holder.timesContactedView.setTextColor(phoneColor);
            holder.numberTextView = (TextView) convertView.findViewById(R.id.search_contact_number);
            holder.numberTextView.setTextColor(phoneColor);
            holder.orgTextView = (TextView) convertView.findViewById(R.id.organizational);
            holder.orgTextView.setTextColor(jobTitleColor);
            holder.quickContact = (RoundImageView) convertView.findViewById(R.id.quickContact);
            holder.quickContact.setRectAdius(Constants.dip2px(mContext,20));
            holder.checkBox = (CheckBox) convertView.findViewById(R.id.isSel);
//            holder.wxIcon = (ImageView) convertView.findViewById(R.id.wx_icon);
            //holder.maskImg = (ImageView) convertView.findViewById(R.id.iv_local_mask);
            holder.inviteImg = (ImageView) convertView.findViewById(R.id.iv_invite_icon);
        } else {
            View footerView = mInflater.inflate(R.layout.search_contact_footerview, null);
            LinearLayout body = (LinearLayout) footerView.findViewById(R.id.footer_body);
            LinearLayout mNull = (LinearLayout) footerView.findViewById(R.id.footer_ll_null);
            TextView text = (TextView) footerView.findViewById(R.id.footer_match_text);
            int match = getCount() - 1;
            // TODO 判断有没有结果
            if (match == 0) {
//                mContext.setNoData(true);
//                footerView.setVisibility(View.GONE);
                body.setVisibility(View.GONE);
                mNull.setVisibility(View.VISIBLE);
            } else {
//                mContext.setNoData(false);
                body.setVisibility(View.VISIBLE);
                mNull.setVisibility(View.GONE);
            }

            StringBuffer sb = new StringBuffer();
            sb.append(match).append("/").append(ContactsDBReader.ALL_CONTACTS_NUMBER);
            String footerText = mContext.getString(R.string.footer_view_match, sb.toString());
            text.setText(footerText);
            text.setTextColor(jobTitleColor);

            text = (TextView) footerView.findViewById(R.id.footer_search_text);

            if (!StringUtil.isEmpty(mCurrentSearchText)) {
                footerText = mContext.getString(R.string.footer_view_search, mCurrentSearchText);
            } else {
                footerText = mContext.getString(R.string.footer_view_search, "");
            }
            text.setText(footerText);
            text.setTextColor(phoneColor);

            TextView line = (TextView) footerView.findViewById(R.id.footer_line);
            line.setText("_____________________");
            line.setTextColor(nameColor);

            return footerView;
        }

        if (mInterrupted) {
            return convertView;
        }

        String nameValue = null;
        long photoId = 0;
        holder.contactId = contactId;
        convertView.setTag(holder);
        Log.d("WeiXin", "value: mWxIds  = " + mWxIds);
//        if (!StringUtil.isEmpty(mWxIds) && mWxIds.contains("," + contactId + ",")) {
//            holder.wxIcon.setVisibility(View.VISIBLE);
//            holder.wxIcon.setImageResource(R.drawable.icon_flag_wx);
//            Log.d("WeiXin", "outSide visible");
//        } else {
//            Log.d("WeiXin", "outSide gone");
//            holder.wxIcon.setVisibility(View.GONE);
//        }
        /*if (mPhoneNumberArea == null) {
            mPhoneNumberArea = new PhoneNumberArea(mContext);
        }*/

        StringBuilder number = null;// = new StringBuilder();
        StringBuilder orgnization = null; //new StringBuilder();
        StringBuilder groupString = null; //new StringBuilder();
        StringBuilder emailString = null; //new StringBuilder();
        StringBuilder area = null; //new StringBuilder();
        StringBuilder noteStr = null; //new StringBuilder();
        boolean isWx = false;

        Person person = mPreferenceUtil.getPerson(contactId + "");//问题

        ArrayList<String> areaList = null; //new ArrayList<String>();
        PhoneNumberArea phoneNumberArea = PhoneNumberArea.getInstance(mContext);

        if (person == null)
        {

            if (mInterrupted) {
                return convertView;
            }

            Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);
            String dataDir = Contacts.Data.CONTENT_DIRECTORY;
            Uri methodUri = Uri.withAppendedPath(contactUri, dataDir);
            Cursor c = null;
            try {
                c = mContext.getContentResolver().query(methodUri,
                      ContactsDBReader.DATA_PROJECTION, null, null, null);
            } catch (IllegalArgumentException e) {
                if (c != null) {
                    c.close();
                }
            }
            if (c != null)
            {
                try
                {
                    while (c.moveToNext()) {
                        if (mInterrupted) {
                            return convertView;
                        }
                        String mime = c.getString(c.getColumnIndex(Data.MIMETYPE));

                        if (Phone.CONTENT_ITEM_TYPE.equals(mime)) {
                            String phoneNumber = c.getString(c.getColumnIndex(Phone.NUMBER));
                            if (!StringUtil.isEmpty(phoneNumber)) {
                                String areaElement = phoneNumberArea.getArea(phoneNumber, false);
                                if (!StringUtil.isEmpty(areaElement)) {
                                    if (areaList == null) {
                                        areaList = new ArrayList<String>();
                                    }
                                    if (!areaList.contains(areaElement)) {
                                        areaList.add(areaElement);
                                    }
                                }
                                if (number == null) {
                                    number = new StringBuilder();
                                }
                                number.append(PhoneNumberArea.formatPhoneNumDisplay(phoneNumber));
                                number.append("\n");
//                                int type = c.getInt(c.getColumnIndex(Phone.TYPE));
//                                if ((String.valueOf(Phone.TYPE_MOBILE)).equals(type)
//                                        && count < 1) {
//                                    count++;
//                                }
                            }

                        } else if (GroupMembership.CONTENT_ITEM_TYPE.equals(mime)) {

                            String groupId = c.getString(c.getColumnIndex(GroupMembership.GROUP_ROW_ID));

                            final HashMap<String, GroupInfo> mGroupList = ContactsDBReader.mGroupList;
                            if (mGroupList != null) {
                                GroupInfo group = mGroupList.get(groupId);
                                if (group != null) {
                                    String groupName = group.mGroupTitle;
                                    if (!StringUtil.isEmpty(groupName)) {
                                        if (groupString == null) {
                                            groupString = new StringBuilder();
                                        }
                                        groupString.append(groupName);
                                        groupString.append(",");
                                    }
                                }
                            }
                        } else if (CommonDataKinds.Email.CONTENT_ITEM_TYPE.equals(mime)) {
                            String email = c
                                  .getString(c
                                        .getColumnIndex(CommonDataKinds.Email.DATA1));
                            if (emailString == null) {
                                emailString = new StringBuilder();
                            }
                            emailString.append(email);
                            emailString.append(",");

                        } else if (CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE.equals(mime)) {
                            nameValue = c.getString(c
                                  .getColumnIndex(CommonDataKinds.StructuredName.DISPLAY_NAME));
                        } else if (CommonDataKinds.Note.NOTE.equals(mime)) {
                            String note = c.getString(c
                                  .getColumnIndex(CommonDataKinds.Note.NOTE));
                            if (noteStr == null) {
                                noteStr = new StringBuilder();
                            }
                            noteStr.append(note).append(',');
                        } else if (Constants.WX_CHAT.equals(mime)) {
                            long contactWxId = c.getLong(c.getColumnIndex(Data.CONTACT_ID));
                            String wx_tag = c.getString(c.getColumnIndex(Data.DATA2));
                            String wx_type = c.getString(c.getColumnIndex(Data.DATA3));
                            if ("微信".equals(wx_tag) && "聊天".equals(wx_type)) {
                                isWx = true;
                            }
                        }
                    }
                } catch (Exception e) {
                    Log.d(TAG, "getAmazingView", e);
                } finally {
                    c.close();
                }

            }

//            photoId = ContactsDBReader.getPhotoId(contactId, mContext);

            if (areaList != null && areaList.size() > 0) {
                if (area == null) {
                    area = new StringBuilder();
                }
                for (String str : areaList) {
                    area.append(str).append(",");
                }
            }
            if (area != null && area.length() > 0) {
                if (groupString == null) {
                    groupString = new StringBuilder();
                }
                groupString.insert(0, area.toString());
            }

            if (noteStr != null && noteStr.length() > 0) {
                groupString.append(noteStr);
            }

//            if (isWx) {
//                holder.wxIcon.setVisibility(View.VISIBLE);
//                holder.wxIcon.setImageResource(R.drawable.icon_flag_wx);
//                Log.d("WeiXin", "inSide visible");
//            } else {
//                Log.d("WeiXin", "inSide gone");
//                holder.wxIcon.setVisibility(View.GONE);
//            }
        }
        else
        {
            if (mInterrupted) {
                return convertView;
            }
            List<Person.PhoneNumber> phoneNumber = person.getPhoneList();
            if (phoneNumber != null && phoneNumber.size() > 0) {
                for (int i = 0; i < phoneNumber.size(); i++) {
                    if (mInterrupted) {
                        return convertView;
                    }
                    String numberElement = phoneNumber.get(i).getNumber();
                    if (number == null) {
                        number = new StringBuilder();
                    }
                    number.append(PhoneNumberArea.formatPhoneNumDisplay(numberElement));
                    number.append("\n");

                    /*String areaElement = phoneNumberArea.getArea(numberElement, false);
                    if (!StringUtil.isEmpty(areaElement)) {
                        if (areaList == null) {
                            areaList = new ArrayList<String>();
                        }
                        if (!areaList.contains(areaElement)) {
                            areaList.add(areaElement);
                        }
                    }*/
                }
            }

            if (person.getGroupIdSetList() != null) {
                List<Person.GroupIdSet> groupIdSet = person.getGroupIdSetList();
                Iterator<GroupIdSet> it = groupIdSet.iterator();
                StringBuilder groupNameAll = new StringBuilder();
                while (it.hasNext()) {

                    if (mInterrupted) {
                        return convertView;
                    }

                    long groupId = it.next().getGroupId();
                    GroupInfo group = ContactsDBReader.mGroupList.get(Long.toString(groupId));
                    String groupName = null;
                    if (group != null) {
                        groupName = group.mGroupTitle;
                    }
                    if (!StringUtil.isEmpty(groupName)) {
                        groupNameAll.append(groupName).append(Constants.GROUPNAME_SPLIT_2DISPLAY);
                    }
                }
                if (groupNameAll.length() > 0) {
                    if (groupString == null) {
                        groupString = new StringBuilder();
                    }
                    groupString.append(groupNameAll.toString());
                }
            }

            String orga = person.getOrganization();
            if (!StringUtil.isEmpty(orga)) {
                if (orgnization == null) {
                    orgnization = new StringBuilder();
                }
                orgnization.append(orga);
            }

            String email = person.getEmail();
            if (!StringUtil.isEmpty(email)) {
                if (emailString == null) {
                    emailString = new StringBuilder();
                }
                emailString.append(email);
            }

            nameValue = person.getDisplayName();
            photoId = person.getPhotoId();

            if (areaList != null && areaList.size() > 0) {

                if (area == null) {
                    area = new StringBuilder();
                }

                for (String str : areaList) {
                    area.append(str).append(",");
                }
            }


            if (area != null && area.length() > 0) {
                if (groupString == null) groupString = new StringBuilder();
                groupString.insert(0, area.toString());
            }

            if (person.hasNote()) {
                if (noteStr == null) noteStr = new StringBuilder();
                if (groupString == null) groupString = new StringBuilder();
                groupString.append(person.getNote());
            }
        }

        if (mInterrupted)
        {
            return convertView;
        }

        // heihei: need refactor
        // and this contacted times must be updated in time at the further version
        int timesContacted = 0;
        if (mPinyinSearch == null) {
            mPinyinSearch = PinyinSearch.getInstance(mContext.getApplicationContext());
        }
        PinyinSearch.ContactInfoNode memoryNode = mPinyinSearch.getContactInfo().get(contactId);
        if (memoryNode == null) {
            timesContacted = ContactsDBReader.getContactedNumber(
                  contactId, mContext.getContentResolver());
        } else {
            timesContacted = memoryNode.contactedNumber;
        }

        if (timesContacted > 0 && mContext.mShowTimesContacted) {
            holder.timesContactedView.setText(
                  mContext.getString(R.string.call_count, timesContacted));
//            holder.timesContactedView.setVisibility(View.VISIBLE);
            holder.timesContactedView.setVisibility(View.GONE);
        } else {
            holder.timesContactedView.setVisibility(View.GONE);
        }

        // scView.nameValue = nameValue;
        if (StringUtil.isEmpty(nameValue)) {
            nameValue = mContext.getString(R.string.unknown);
        }

        holder.nameTextView.setText(nameValue);
        holder.nameTextView.setTextSize(mContext.mFontSizeValue);

        boolean nameMatch = false;
        if (!StringUtil.isEmpty(mCurrentSearchText) && mPinyinSearch.mContactIdPosition != null) {
            PinyinSearch.HighLightFormat result = mPinyinSearch.mContactIdPosition.get(contactId);
            if (result != null) {
                nameMatch = true;
                Spannable wordtoSpan = new SpannableString(nameValue);
//                Pattern pattern = Pattern.compile("\\s");
//                Matcher matcher = pattern.matcher(nameValue);
//                if (matcher.find()) {
//                    int count = matcher.groupCount();
//                    for (int i = 0; i < count; i++) {
//                        String str = matcher.group(i);
//                    }
//                }
                int positionNew = 0;
                int startPosition = -1;
                int blankNumber = 0;
                int rankLevel = result.rankLevel;
                int nameLength = result.matchnameLength;
                if (nameValue.indexOf(" ") != -1) {
                    char[] valueArray = nameValue.toCharArray();
                    for (int i = 0; i < valueArray.length; i++) {
                        if (!Character.isWhitespace(valueArray[i])) {
                            if (positionNew == rankLevel) {
                                startPosition = i;
                                int length = 0;
                                for (int j = i + 1; j < valueArray.length; j++) {
                                    if (!Character.isWhitespace(valueArray[j])) {
                                        length++;
                                        if (length == nameLength) {
                                            break;
                                        }
                                    } else {
                                        blankNumber++;
                                    }
                                }
                                break;
                            }
                            positionNew++;
                        }
                    }
                    rankLevel = startPosition;
                    nameLength += blankNumber;
                }
                /*if (selectedId != null) {
                    if (selectedId.equals(holder.contactId)) {
                        hightLightColor = Color.WHITE;
                    } else {
                        hightLightColor = highLightColorBck;
                    }
                } else {
                    hightLightColor = highLightColorBck;
                }*/
                hightLightColor = highLightColorBck;

                if (rankLevel >= nameValue.length() && nameLength > 0) {

                } else if (((rankLevel + nameLength) > nameValue.length()) && (rankLevel < nameValue.length()) && rankLevel >= 0) {
                    wordtoSpan.setSpan(new ForegroundColorSpan(hightLightColor), rankLevel, nameValue.length(),
                          Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                } else {
                    wordtoSpan.setSpan(new ForegroundColorSpan(hightLightColor), rankLevel, rankLevel
                          + nameLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
                holder.nameTextView.setText(wordtoSpan);
            }
        }

        if (mInterrupted) {
            return convertView;
        }

        if (!mDisplayNameOnly) {
            if (number != null && number.length() > 0) {
                holder.phoneNum = number.toString();

                number = number.deleteCharAt(number.length() - 1);
                if (nameMatch || StringUtil.isEmpty(mCurrentSearchText)) {
                    holder.numberTextView.setText(number.toString());
                    holder.numberTextView.setVisibility(View.VISIBLE);
                } else if (!StringUtil.isEmpty(mCurrentSearchText)) {
                    int firstIndex = number.toString().indexOf(mCurrentSearchText);
                    int matchLength = 0;
                    if (firstIndex == -1) {
                        firstIndex = 0;
                        matchLength = number.length();
                    } else {
                        matchLength = mCurrentSearchText.length();
                    }
                    if (selectedId != null) {
                        if (selectedId.equals(holder.contactId)) {
                            hightLightColor = Color.WHITE;
                        } else {
                            hightLightColor = highLightColorBck;
                        }
                    } else {
                        hightLightColor = highLightColorBck;
                    }
                    Spannable numbertoSpan = new SpannableString(number);
                    numbertoSpan.setSpan(new ForegroundColorSpan(hightLightColor), firstIndex, firstIndex
                          + matchLength, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    holder.numberTextView.setText(numbertoSpan);
                }
            } else {
                // scView.number.setVisibility(View.GONE);
                String noPhone = mContext.getResources().getString(R.string.no_number);
                holder.phoneNum = noPhone;
                holder.numberTextView.setText(noPhone);
                holder.numberTextView.setVisibility(View.VISIBLE);
            }
        } else {
            if (number != null && number.length() > 0) {
                holder.phoneNum = number.toString();
                String[] temp = holder.phoneNum.split("\n");
                holder.numberTextView.setText(temp[0]);
            } else {
                // scView.number.setVisibility(View.GONE);
                String noPhone = mContext.getResources().getString(R.string.no_number);
                holder.phoneNum = noPhone;
                holder.numberTextView.setText(noPhone);
                holder.numberTextView.setVisibility(View.VISIBLE);
            }

        }

        final String num = holder.numberTextView.getText().toString();
        holder.inviteImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonCodeUtil.launchSendMessage(
                      mContext, num,
                      "【"+mMyName+"】邀请您下载“团队”软件，点击"+ AsynHttpClient.HTTP_TEAM_DOWNLOAD + " 接受邀请，免费聊天。"
                );

            }
        });


        // remove last comma if organization is null
//        StringBuilder organizationalText = null; //new StringBuffer();

        // TODO 号码归属地暂时去掉
        /*int groupLength = 0;
        if (groupString != null) groupLength = groupString.length();

        int orgLength = 0;
        if (orgnization != null) orgLength = orgnization.length();

        if (groupLength > 0) {
            if (orgLength > 0) {
                if (groupString.charAt(groupLength - 1) != ',') {
                    groupString.append(",");
                }
            } else {
                if (groupString.charAt(groupLength - 1) == ',') {
                    groupString.deleteCharAt(groupLength - 1);
                }
            }
//            if (organizationalText == null) {
//                organizationalText = new StringBuilder();
//            }
//            organizationalText.append(groupString);
        }

        if (orgLength > 0) {
            if (orgnization.charAt(orgLength - 1) == ',') {
                orgnization = orgnization.deleteCharAt(orgLength - 1);
            }
//            if (organizationalText == null) {
//                organizationalText = new StringBuilder();
//            }
//            organizationalText.append(orgnization);
        }
        if ((groupString != null || orgnization != null) && !mDisplayNameOnly) {
            holder.orgTextView.setText(((groupString != null && !StringUtil.isEmpty(groupString.toString())) ? groupString.toString() : "本地电话") +
                    ((orgnization != null) ? orgnization.toString() : ""));
            holder.orgTextView.setVisibility(View.VISIBLE);
        } else {
            holder.orgTextView.setVisibility(View.GONE);
        }*/

        String registPhone = null;
        if (LocalLogin.getInstance().isLogedin()) {
            if (mCloudUser == null || mCloudUser.size() == 0) {
                mCloudUser = (HashMap<Long, String>) mPreferenceUtil.getCloudContact(PreferenceUtil.CLOUD_REGIST_USER);

                if (mCloudUser == null) {
                    mCloudUser = new HashMap<Long, String>();
                    // 防止本地通信录崩溃
                    mCloudUser.put(0L, "0");
                }
            }
            registPhone = mCloudUser.get(contactId);
        }
        if (registPhone != null) {//注册的
            holder.inviteImg.setVisibility(View.GONE);
            holder.contactDisturbStatus.setVisibility(View.VISIBLE);
        } else {//未注册的
            holder.inviteImg.setVisibility(View.VISIBLE);
            holder.contactDisturbStatus.setVisibility(View.GONE);
        }
        if (mIfCheckBoxShow) {
            holder.checkBox.setVisibility(View.VISIBLE);
            holder.inviteImg.setVisibility(View.GONE);
//            holder.contactDisturbStatus.setVisibility(View.GONE);
            if (registPhone != null) {//注册的
                holder.checkBox.setButtonDrawable(R.drawable.checkbox_sel_bulksms);
            } else {//没注册的
                if (isHaveUnClickable) {
                    holder.checkBox.setButtonDrawable(R.drawable.check_unclickable);
                } else {
                    holder.checkBox.setButtonDrawable(R.drawable.checkbox_sel_bulksms);
                }
            }

            if (mContactIdSelected.contains(holder.contactId)) {
                holder.checkBox.setChecked(true);
            } else {
                holder.checkBox.setChecked(false);
            }
            /*if (mIsPhotoShow) {
                holder.quickContact.setVisibility(View.GONE);
            }*/
        } else {
            holder.checkBox.setVisibility(View.GONE);
        }

        Integer status = null;
        if (LocalLogin.getInstance().isLogedin()) {
            status = mCloudUserData.get(contactId);
        }


//        if (registPhone == null && isHaveUnClickable) {
//        } else {
        convertView.setOnClickListener(this);
//        }
        convertView.setOnLongClickListener(this);

        if (mIsPhotoShow) {
            if (photoId <= 0) {
                holder.quickContact.setImageDrawable(getNoNameDrawable());
            } else {
                Bitmap bitmap = ContactsDBReader.getPhoto(mContext, photoId);

                if (bitmap == null){
                    holder.quickContact.setImageDrawable(getNoNameDrawable());
                }else{
                    //bitmap = PhotoUtil.compressAvatarIv(bitmap);
                    holder.quickContact.setImageBitmap(bitmap);
                }

                /*if (bitmap == null) ((BitmapDrawable) getNoNameDrawable()).getBitmap();

                if (status != null) {
//                    bitmap = compressIcon(bitmap, AllDialogUtil.getBitmapByStatus(mContext, contactId), 1.5f);
                    //bitmap = PhotoUtil.compressImage(mContext, bitmap, 100, 100);
                    bitmap = PhotoUtil.compressAvatarIv(bitmap);
                }
                holder.quickContact.setImageBitmap(bitmap);*/
            }
            holder.quickContact.setVisibility(View.VISIBLE);
        } else {
            holder.quickContact.setVisibility(View.GONE);
        }
        TextView tv = (TextView) convertView.findViewById(R.id.composer_header);
        tv.setBackgroundColor(headerColor);
        tv.setTextColor(headerTextColor);
        /*if (selectedId != null) {
            if (selectedId.equals(holder.contactId)) {
                setSelectedStatus(convertView);
            } else {
                clearSelectedStatus(convertView);
            }
        }*/
        return convertView;
    }


    private Bitmap compressIcon(Bitmap src, Bitmap statusBitmap, float scale) {
        Paint p = new Paint();
        Bitmap b = Bitmap.createBitmap(src.getWidth(), src.getHeight(),
              Bitmap.Config.ARGB_8888);

        Matrix m = new Matrix();
        Canvas c = new Canvas(b);
        c.drawBitmap(src, m, p);
        m.postScale(scale, scale);
        m.postTranslate(src.getWidth() - scale * statusBitmap.getWidth(),
              src.getHeight() - scale * statusBitmap.getHeight());
        c.drawBitmap(statusBitmap, m, p);
        return b;
    }

    @Override
    public void configurePinnedHeader(View header, int position, int alpha) {
        TextView lSectionHeader = (TextView) header.findViewById(R.id.header);
//        TextView lSectionHeader = (TextView) header;
        int section = getSectionForPosition(position);
        if (section != -1) {
            lSectionHeader.setText(getSections()[section]);
        }
//        lSectionHeader.setBackgroundColor(alpha << 24 | (0xbbffbb));
//        lSectionHeader.setTextColor(alpha << 24 | (0x000000));
    }

    @Override
    public int getPositionForSection(int section) {
        if (section < 0) {
            section = 0;
        }

        int contactsIdSize = getAllContactsIdSize();
        if (section >= contactsIdSize) {
            section = contactsIdSize - 1;
        }
        int c = 0;
        for (int i = 0; i < contactsIdSize; i++) {
            if (section == i) {
                return c;
            }
            c += mAllContactsIdBySection.get(i).second.size();
        }
        return 0;
    }

    @Override
    public int getSectionForPosition(int position) {
        int c = 0;

        int size = getAllContactsIdSize();
        for (int i = 0; i < size; i++) {
            if (position >= c && position < c + mAllContactsIdBySection.get(i).second.size()) {
                return i;
            }
            c += mAllContactsIdBySection.get(i).second.size();
        }
        return -1;
    }

    private int getAllContactsIdSize() {
        if (mAllContactsIdBySection == null) {
            return 0;
        }

       /* if (mInterrupted) {
            return 0;
        }*/

        return mAllContactsIdBySection.size();
    }

    @Override
    public String[] getSections() {

        int size = getAllContactsIdSize();
        String[] res = null;

        if (size > 0) {
            res = new String[size];
            for (int i = 0; i < size; i++) {
                res[i] = mAllContactsIdBySection.get(i).first;
            }
        }
        return res;
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        if (key.equals(PreferenceUtil.CONTACT_ISDISPLAYPHOTO)) {
            mIsPhotoShow = mPreferenceUtil.get(PreferenceUtil.CONTACT_ISDISPLAYPHOTO,
                  Boolean.class);
        } else if (key.equals(PreferenceUtil.CONTACT_NAME_SORT)) {
//            mOrderBy = dialerapp.getPreferenceUtil().get(PreferenceUtil.CONTACT_NAME_SORT, Integer.class);
        } else if (PreferenceUtil.DISPLAY_NAME_ONLY.equals(key)) {
            mDisplayNameOnly = mPreferenceUtil.get(PreferenceUtil.DISPLAY_NAME_ONLY,
                  Boolean.class);
        }
    }

    @Override
    public boolean onLongClick(View paramView) {
//        if (mContext.getDmg().getCurrentPage() != 1) {
//            mContext.getDmg().setSelect(1, true);
//            return true;
//        }
        mTouchView = paramView;
        ContactEntryHolder holder = (ContactEntryHolder) mTouchView.getTag();
        if (holder == null) {
            return true;
        }

        if (mIfCheckBoxShow) {
            return true;
        }

        boolean ifLongClickDial = mPreferenceUtil.getPreference().getBoolean(PreferenceUtil.LONG_CLICK_DIAL, true);
        if (ifLongClickDial) {
            String numberText = holder.phoneNum;
            String[] mPhoneNumber = null;
            if (!StringUtil.isEmpty(numberText)) {
                mPhoneNumber = numberText.split("\n");
            }
            if (mPhoneNumber != null && !mPhoneNumber[0].equals(mContext.getString(R.string.no_number))) {
                String number = holder.phoneNum;
                String[] phoneNumber = number.split("\n");
                if (phoneNumber.length == 0) {
                    return true;
                }

                if (!TextUtils.isEmpty(mContext.getFilterText())) {
                    // mContext.noNeedToRefresh = true;
//                    mContext.setFilterText("");
                }

//                CommonCodeUtil.launchCallByNumber(mContext, mPhoneNumber[0]);
            } else {
                String url = null;
                String dataDir = Contacts.Data.CONTENT_DIRECTORY;
                Uri methodUri = Uri.withAppendedPath(ContentUris.withAppendedId(
                      Contacts.CONTENT_URI, holder.contactId), dataDir);
                Cursor c = mContext.getContentResolver().query(methodUri,
                      ContactsDBReader.DATA_PROJECTION, null, null, null);
                while (c.moveToNext()) {
                    String mime = c.getString(c.getColumnIndex(Data.MIMETYPE));
                    if (Website.CONTENT_ITEM_TYPE.equals(mime)) {
                        url = c.getString(c.getColumnIndex(Website.URL));
                        break;
                    }
                }

//                if (!TextUtils.isEmpty(url)) {
//                    ContactInfoActivity.go2Url(mContext, url);
//                } else {
//                    IphoneDialogUtil.showCustomMessageOK(mContext, -1,
//                            R.string.dialog_label_dial_none, R.string.dialog_label_dial_btn);
//                }
            }
        } else {
            //setSelectedStatus(mTouchView);
//            enterDisplayCommunication(holder);
        }
        return true;
    }

    @Override
    public void onClick(View paramView) {

        ContactEntryHolder holder = (ContactEntryHolder)paramView.getTag();
        selectedId = holder.contactId;
        /*if (mTouchView != null) {
            ContactEntryHolder h = (ContactEntryHolder)mTouchView.getTag();
            if (h == null) {
                return;
            }
            if (!h.contactId.equals(holder.contactId)) {
                clearSelectedStatus(mTouchView);
                notifyDataSetChanged();
            }

        }*/

        mTouchView = paramView;

        String numberText = holder.phoneNum;
        String[] mPhoneNumber = null;
        if (!StringUtil.isEmpty(numberText)) {
            mPhoneNumber = numberText.split("\n");
        }

        boolean longClickDial = mContext.mLongClickDial;
        if (!mIfCheckBoxShow)
        {

            if (!longClickDial)
            {
                if (mPhoneNumber != null && !mPhoneNumber[0].equals(mContext.getResources().getString(
                      R.string.no_number))) {
                    String number = holder.numberTextView.getText().toString();
                    String[] phoneNumber = number.split("\n");
                    if (phoneNumber.length == 0) {
                        return;
                    }

                    if (!TextUtils.isEmpty(mContext.getFilterText())) {
                        // mContext.noNeedToRefresh = true;
//                        mContext.setFilterText("");
                    }

                    CommonCodeUtil.launchCallByNumber(mContext, mPhoneNumber[0]);
                }
                else
                {
                    String url = null;
                    String dataDir = Contacts.Data.CONTENT_DIRECTORY;
                    Uri methodUri = Uri.withAppendedPath(ContentUris.withAppendedId(
                          Contacts.CONTENT_URI, holder.contactId), dataDir);
                    Cursor c = mContext.getContentResolver().query(methodUri,
                          ContactsDBReader.DATA_PROJECTION, null, null, null);
                    while (c.moveToNext())
                    {
                        String mime = c.getString(c.getColumnIndex(Data.MIMETYPE));
                        if (Website.CONTENT_ITEM_TYPE.equals(mime))
                        {
                            url = c.getString(c.getColumnIndex(Website.URL));
                            break;
                        }
                    }

//                    if (!TextUtils.isEmpty(url)) {
//                        ContactInfoActivity.go2Url(mContext, url);
//                    } else {
//                        IphoneDialogUtil.showCustomMessageOK(mContext, -1,
//                                R.string.dialog_label_dial_none, R.string.dialog_label_dial_btn);
//                    }
                }
            } else {
                /*setSelectedStatus(mTouchView);
                notifyDataSetChanged();*/
                enterDisplayCommunication(holder);
            }
            //更新联系人状态
            updateContactStatus(holder);
        }
        else
        {
            if (mCloudUser.get(selectedId) == null && isHaveUnClickable) {
                Toast.makeText(mContext, "该用户未注册，不能进行如下操作", Toast.LENGTH_SHORT).show();
            } 
            /*else if (mPreferenceUtil.getString(PreferenceUtil.CLIENT_USEID, "－1").equals(mCloudUser.get(selectedId))) {
                Toast.makeText(mContext, "对不起，您不能选择自己", Toast.LENGTH_SHORT).show();
            } */
            else {
                boolean isCheck = holder.checkBox.isChecked();
                holder.checkBox.setChecked(!isCheck);
                //setSelectedStatus(mTouchView);
                long cloudId = 0;
                try {
                    HashMap<Long, HashSet<Long>> contactId2CloudId = (HashMap<Long, HashSet<Long>>) PreferenceUtil.getInstance(mContext).getCloudContact(PreferenceUtil.CONTACT_ID_2_CLOUD_ID);
                    if (holder != null) {
                        HashSet<Long> cloudIdSet = contactId2CloudId.get(holder.contactId);
                        cloudId = cloudIdSet.iterator().next();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                ChatContact chatContact = new ChatContact(cloudId + "", holder.nameTextView.getText().toString(), mPhoneNumber[0] + "", holder.contactId + "");
                if (isCheck) {
                    mContactSelected.remove(chatContact);
                    mContactIdSelected.remove(holder.contactId);
                } else {
                    mContactSelected.add(chatContact);
                    mContactIdSelected.add(holder.contactId);
//                if (mContext.checkboxSelectedFor(Constants.CHECKBOX_STATUS_BUSINESSCARD)) {
//                    showNameCardMessage(holder, mTouchView);
//                } else if (mContext.checkboxSelectedFor(Constants.CHECKBOX_STATUS_SELECT_BLACKLIST) ||
//                        mContext.checkboxSelectedFor(Constants.CHECKBOX_STATUS_SELECT_WHITELIST)) {
//                    showBlackWhitelistMessage(holder);
//                } else if (mContext.checkboxSelectedFor(Constants.CHECKBOX_STATUS_SAVE2_OLD_CONTACT)) {
//                    showSave2OldContact(holder);
//                }//need open
                }

                mContext.sendMessageToHandler(Constants.FRESH_SEND_BUTTON_NUMBER);
                // List<Long> list = null;
                //List<Long> newList = new ArrayList<Long>();
                /*
                for (Pair<String, List<Long>> item : mAllContactsIdBySection)
                {
                    if (isHaveUnClickable) 
                    {
                        //list = new ArrayList<Long>();
                        for (Long id : item.second)
                        {
                            if (isHaveUnClickable && mCloudUser.get(id) == null) 
                            {
                            } 
                            else 
                            {
                                //list.add(id);
                            	sumvalid++;
                            }
                        }
                        //newList.addAll(list);
                        
                    }
                    else 
                    {
                        //list = item.second;
                        //newList.addAll(list);
                    }
                }
                */
                List<Long> getlist = getChangeContentId();
                int sumvalid = getlist.size();

                if( mContactIdSelected.size() >= sumvalid )
                {
                    mContext.setSelectImage(true);
                    //mContext.mCbSelectAll.setChecked(true);
                }
                else
                {
                    mContext.setSelectImage(false);
                    //mContext.mCbSelectAll.setChecked(false);
                }
            }

            notifyDataSetChanged();

        }
        mTouchView.setSelected(false);

    }

    private void enterDisplayCommunication(ContactEntryHolder holder) {
        Intent intent = new Intent(mContext, ContactDetailActivity.class);
        intent.setAction(ContactDetailActivity.ACTION_CONTACT);
        intent.putExtra(Constants.INTENT_FLAG_CONTACTID, holder.contactId);
        mContext.startActivityForResult(intent,
              Constants.ACTIVITY_REQUEST_DISPLAYCOMMUNICATION);
    }
//
//    private void showSave2OldContact(final ContactEntryHolder holder) {
//        new AlertDialog.Builder(mContext)
//                .setMessage(mContext.getString(R.string.save2_old_contact_msg,
//                        mContext.mPhoneNum, holder.nameTextView.getText()))
//                .setNegativeButton(R.string.ok, new DialogInterface.OnClickListener() {
//
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        long rawId = ContactsDBReader.getRawContactId(mContext.getContentResolver(),
//                                holder.contactId);
//
//                        ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
//                        ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
//                        builder.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
//                        builder.withValue(Phone.TYPE, Phone.TYPE_MOBILE);
//                        builder.withValue(Phone.NUMBER, mContext.mPhoneNum);
//                        builder.withValue(Data.RAW_CONTACT_ID, rawId);
//
//                        operationList.add(builder.build());
//
//                        ContentProviderResult[] res = null;
//                        try {
//                            res = mContext.getContentResolver().applyBatch(
//                                    ContactsContract.AUTHORITY, operationList);
//                        } catch (RemoteException e) {
//                            e.printStackTrace();
//                        } catch (OperationApplicationException e) {
//                            e.printStackTrace();
//                        }
//
//                        if (res != null) {
//                            Toast.makeText(mContext, R.string.save_as_new_success,
//                                    Toast.LENGTH_LONG).show();
//                        } else {
//                            Toast.makeText(mContext, R.string.save_as_new_failure,
//                                    Toast.LENGTH_LONG).show();
//                        }
//
//                        if (mContext.mDisplayCallLog) {
//                            mContext.mListStatus = ListStatus.ENUM_SHOW_CALL_LOG;
//                            mContext.mDisplayCallLog = false;
//                        }
//                        clearSelectedStatus(mTouchView);
//                        mContext.quitSelectedStatus(Constants.CHECKBOX_STATUS_SAVE2_OLD_CONTACT);
//                        mContext.freshContactsByStatus();
//                    }
//                })
//                .setPositiveButton(R.string.cancel, new DialogInterface.OnClickListener() {
//
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        if (mContext.mDisplayCallLog) {
//                            mContext.mListStatus = ListStatus.ENUM_SHOW_CALL_LOG;
//                            mContext.mDisplayCallLog = false;
//                        }
//                        clearSelectedStatus(mTouchView);
//                        mContext.quitSelectedStatus(Constants.CHECKBOX_STATUS_SAVE2_OLD_CONTACT);
//                        mContext.freshContactsByStatus();
//                    }
//                })
//                .setOnCancelListener(new OnCancelListener() {
//
//                    @Override
//                    public void onCancel(DialogInterface dialog) {
//                        if (mContext.mDisplayCallLog) {
//                            mContext.mListStatus = ListStatus.ENUM_SHOW_CALL_LOG;
//                            mContext.mDisplayCallLog = false;
//                        }
//                        clearSelectedStatus(mTouchView);
//                        mContext.quitSelectedStatus(Constants.CHECKBOX_STATUS_SAVE2_OLD_CONTACT);
//                        mContext.freshContactsByStatus();
//                    }
//                })
//                .show();
//    }

    private void updateContactStatus(ContactEntryHolder holder) {
        Integer status = mCloudUserData.get(holder.contactId);
        if (status != null) {
            mCloudUserData.put(holder.contactId, AllDialogUtil.setReaded(status));
            mPreferenceUtil.saveCloudContact(PreferenceUtil.CONTACT_ID_2_DIST_STATUS,
                  mCloudUserData);
            notifyDataSetChanged();
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        /*if (scrollState == OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
            mContext.setKeypadInVisible();
        }*/
    }

//    public void showNameCardMessage(final ContactEntryHolder holder, final View view) {
//        final String contactName = holder.nameTextView.getText().toString();
//        String blurb = mContext.getString(R.string.namecard_set_hint, contactName);
//        final long contactId = holder.contactId;
//        AllDialogUtil dialog = AllDialogUtil.getInstance(mContext);
//        dialog.titleMsgBtnStyle("提示", blurb, mContext.getString(R.string.ok), mContext.getString(R.string.cancel));
//        dialog.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {
//
//            @Override
//            public void onConfirmClick(Dialog lDialog) {
//                lDialog.dismiss();
//         /*       Intent intent = null;
//                if (mContext.ifGoogleMapActive()) {
//                    intent = new Intent(mContext, SendCardActivity.class);
//                } else {
//                    intent = new Intent(mContext, SendCardActivityNoMap.class);
//                }*/
////                intent.putExtra(Constants.CONTACT_ID_KEY, holder.contactId);
//                mPreferenceUtil.save(PreferenceUtil.NAMECARD_CONTACTID, contactId);
//                if (mContext.mDisplayCallLog) {
//                    mContext.mListStatus = ListStatus.ENUM_SHOW_CALL_LOG;
//                    mContext.mDisplayCallLog = false;
//                }
//                clearSelectedStatus(view);
//                mContext.quitSelectedStatus(Constants.CHECKBOX_STATUS_BUSINESSCARD);
//                mContext.getDmg().setSelect(2, true);
//                mContext.sendMessageToHandler(Constants.SET_TAB_VISIBLE);
//               /* mContext.startActivityForResult(intent, Constants.ACTIVITY_REQUEST_SHARE_NAMECARD);
//                mContext.overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);*/
//
//            }
//
//            @Override
//            public void onCancelClick(Dialog lDialog) {
//                holder.checkBox.setChecked(false);
//                mContactIdSelected.remove(holder.contactId);
//                lDialog.dismiss();
//            }
//        });
//        dialog.setOnDialogCancelableListener(new AllDialogUtil.DialogOnCancelableListener() {
//
//            @Override
//            public void onCancelable(Dialog lDialog) {
//                holder.checkBox.setChecked(false);
//                mContactIdSelected.remove(holder.contactId);
//                lDialog.dismiss();
//            }
//        });
//    }

//    public void showBlackWhitelistMessage(final ContactEntryHolder holder) {
//
//        final boolean showBlacklist = mContext.checkboxSelectedFor(Constants.CHECKBOX_STATUS_SELECT_BLACKLIST);
//        final String contactName = holder.nameTextView.getText().toString();
//        Resources res = mContext.getResources();
//        String blurb;
//        if (showBlacklist) {
//            blurb = mContext.getString(R.string.blacklist_set_hint, contactName);
//        } else {
//            blurb = mContext.getString(R.string.whitelist_set_hint, contactName);
//        }
//        final List<String> allPhoneNumbers = ContactsDBReader.getContactAllNumbers(
//                mContext.getContentResolver(), String.valueOf(holder.contactId));
//
//        AllDialogUtil dialogUtil = AllDialogUtil.getInstance(mContext);
//        dialogUtil.titleMsgBtnStyle("提示", blurb, res.getString(R.string.ok), res.getString(R.string.cancel));
//        dialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {
//
//            @Override
//            public void onConfirmClick(Dialog lDialog) {
//
//                lDialog.dismiss();
//                Intent intent = new Intent(mContext, BlackListActivity.class);
//                intent.putExtra(BlackListActivity.SHOW_BLACK_LIST, showBlacklist);
//
//                mIfCheckBoxShow = false;
//
//                if (allPhoneNumbers != null && allPhoneNumbers.size() > 0) {
//                    ContactsDBReader.deleteCommunicationRule(mContext.getContentResolver(), holder.contactId);
//                    ContactsDBReader.insertCommunicationRule(mContext.getContentResolver(),
//                            allPhoneNumbers, holder.contactId, holder.nameTextView.getText().toString(),
//                            showBlacklist);
//                }
//
//                mContext.gotoBlackListActivity();
//                mContext.clearCheckboxStatus();
//                mContext.sendMessageToHandler(Constants.SET_TAB_VISIBLE);
//
//            }
//
//            @Override
//            public void onCancelClick(Dialog lDialog) {
//                holder.checkBox.setChecked(false);
//                mContactIdSelected.remove(holder.contactId);
//                lDialog.dismiss();
//            }
//        });
//        dialogUtil.setOnDialogCancelableListener(new AllDialogUtil.DialogOnCancelableListener() {
//
//            @Override
//            public void onCancelable(Dialog lDialog) {
//                holder.checkBox.setChecked(false);
//                mContactIdSelected.remove(holder.contactId);
//                lDialog.dismiss();
//            }
//        });
//
//    }

    public void destroy() {

    }

}
